package com.xz.spi.javassit.proxy;

import com.xz.simplerpc.api.HelloService;
import com.xz.simplerpc.provider.HelloServiceImpl;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * Created by FangXz on 2018/1/3.
 */
public class JavassistProxyFactory implements InvocationHandler {
    private Object target;

    public JavassistProxyFactory(Object target) {
        this.target = target;
    }

    /*
     * @see cc.lixiaohui.simplerpc.javassist.proxy.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
     */
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("------- intercept before --------");
        // 调用原来的方法
        Object result = method.invoke(target, args);
        System.out.println("--------intercept after ---------");
        return result;
    }
    // 获取代理类的对象
    public Object getProxy() throws Exception {
        return Proxy.newInstance(Thread.currentThread().getContextClassLoader(), target.getClass(), this);
    }

    public static void main(String[] args) throws Exception {
        HelloService helloService = new HelloServiceImpl();
        Object proxy = new JavassistProxyFactory(helloService).getProxy();
        System.out.println(((HelloService) proxy).hello("fingal"));

        System.out.println("package: " + proxy.getClass().getPackage().getName());
        System.out.println("classname: " + proxy.getClass().getName());
        System.out.println("modifiers: " + Modifier.toString(proxy.getClass().getModifiers()));
    }
}
